﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.Move
{
    public partial class FrmPrepareCancel : Form
    {
        bool flag = false;
        bool result = false;
        public FrmPrepareCancel()
        {
            InitializeComponent();
        }

        private void txt_SerialNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //判断物料条码还是单据号
                string strSql = string.Format(@"SELECT Lock_Flag,MaterialCode FROM dbo.T_Bllb_StockInfo_tbsi WHERE SerialNumber='{0}'", txt_SerialNumber.Text.Trim());
                DataTable dt_stock = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                #region 物料
                //判断物料是否处于备料状态
                if (dt_stock.Rows.Count > 0)
                {
                    if (SqlInput.ChangeNullToString(dt_stock.Rows[0]["Lock_Flag"]) != "6")//判断是否处于备料状态
                    {
                        ShowInfo("物料不处于备料状态", false);
                        return;
                    }
                    strSql = string.Format(@"SELECT TOP 1 A.TBDS_ID, A.S_Doc_NO,A.QTY,A.MaterialCode,C.WEBAPI_URL FROM dbo.T_Bllb_StorageDocDetail_tbsdd A
LEFT JOIN dbo.T_Bllb_StorageDoc_tbsd B ON A.S_Doc_NO=B.S_Doc_NO
LEFT JOIN dbo.T_Bllb_DocType_tbdt C ON B.S_Doc_Type=C.TYPE_CODE
WHERE A.SerialNumber='{0}' AND C.Prepare_Flag='Y' ORDER BY A.Create_Time DESC",txt_SerialNumber.Text.Trim());
                    DataTable dt_doc= Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if(dt_doc.Rows.Count>0)
                    {
                        string doc_no = SqlInput.ChangeNullToString(dt_doc.Rows[0]["S_Doc_NO"]);
                        string MaterialCode = SqlInput.ChangeNullToString(dt_doc.Rows[0]["MaterialCode"]);
                        int QTY = SqlInput.ChangeNullToInt(dt_doc.Rows[0]["QTY"], 0);
                        string TBDS_ID = SqlInput.ChangeNullToString(dt_doc.Rows[0]["TBDS_ID"]);
                        //减少已备料数量
                        strSql = string.Format(@"UPDATE dbo.T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY-{2} WHERE S_Doc_NO='{0}' AND MaterialCode='{1}' ",doc_no,MaterialCode,QTY);
                        if (TBDS_ID != string.Empty)//SMT段备料需要处理的数据
                        {
                            strSql += string.Format(@"UPDATE T_Bllb_StorageDocSMT_tbds SET QTY=QTY-{1} WHERE TBDS_ID='{0}' ", TBDS_ID, QTY);
                        }
                        //删除物料SN在备料的中信息
                        strSql += string.Format(@"DELETE FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}' AND SerialNumber='{1}' ", doc_no, MaterialCode);
                        //修改物料SN的状态
                        strSql += string.Format(@"UPDATE dbo.T_Bllb_StockInfo_tbsi SET Lock_Flag='0',SfcNo='' WHERE SerialNumber='{0}' ",txt_SerialNumber.Text.Trim());
                        //物料操作日志
                        strSql += string.Format(@"INSERT INTO T_Bllb_MaterialLog_tbml(SerialNumber,CreateTime,OperateType,MaterialCode,QTY,Creator,Memo,SfcNo,PLCode)
VALUES('{0}',GETDATE(),'{1}','{2}','{3}','{4}','{5}','{6}','{7}') ", txt_SerialNumber.Text.Trim(), "取消备料", MaterialCode, QTY, Utils.uContext.UserIDk__BackingField, "单据" + doc_no, "", "");
                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                        ShowInfo("取消备料成功", true);
                        return;
                    }
                    else
                    {
                        ShowInfo("物料没有备料记录", false);
                        return;
                    }               
                 
                }
                #endregion

                #region 单据
                strSql = string.Format(@"SELECT TOP 1 B.S_Doc_NO FROM T_Bllb_StorageDoc_tbsd B 
WHERE (B.S_Doc_NO='{0}' OR B.SfcNo ='{0}') AND B.S_Doc_Type='7' ORDER BY B.Create_Time DESC
", txt_SerialNumber.Text.Trim());
                DataTable dt_doc2 = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_doc2.Rows.Count > 0)
                {
                    string doc_no = SqlInput.ChangeNullToString(dt_doc2.Rows[0]["S_Doc_NO"]);
                    //获取取消备料的物料汇总信息
                    strSql = string.Format(@"SELECT SUM(QTY) SUM_QTY,MaterialCode FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO ='{0}' AND RECEIVE_FLAG='N' GROUP BY MaterialCode", doc_no);
                    DataTable dt_material = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    #region SMT
                    //SMT段专有处理，获取可取消备料的物料明细
                    strSql = string.Format(@"SELECT A.TBDS_ID, A.S_Doc_NO,A.QTY,A.MaterialCode FROM dbo.T_Bllb_StorageDocDetail_tbsdd A WHERE A.S_Doc_NO ='{0}' AND A.RECEIVE_FLAG='N' and A.TBDS_ID!=''", doc_no);
                    DataTable dt_tbds_id = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    strSql = string.Empty;
                    if (dt_tbds_id.Rows.Count > 0)//
                    {
                        foreach (DataRow dr in dt_tbds_id.Rows)
                        {
                            strSql += string.Format(@" UPDATE T_Bllb_StorageDocSMT_tbds SET QTY=QTY-{1} WHERE TBDS_ID='{0}' ", dr["TBDS_ID"], dr["QTY"]);
                        }
                    }
                    #endregion
                    #region 公共处理
                    if (dt_material.Rows.Count > 0)
                    {
                        string materialcode = SqlInput.ChangeNullToString(dt_material.Rows[0]["MaterialCode"]);//未交接的物料
                        int SUM_QTY = SqlInput.ChangeNullToInt(dt_material.Rows[0]["SUM_QTY"], 0);//未交接物料总数
                        strSql = string.Format(@"UPDATE dbo.T_Bllb_StockInfo_tbsi SET Lock_Flag='0' WHERE SerialNumber in (SELECT SerialNumber FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}' and Receive_Flag ='N') ", txt_SerialNumber.Text.Trim());

                        strSql += string.Format(@"UPDATE dbo.T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY-{2} WHERE S_Doc_NO='{0}' and MaterialCode='{1}' ", doc_no, materialcode, SUM_QTY);

                        strSql += string.Format(@"DELETE FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}' AND RECEIVE_FLAG='N' ", doc_no);

                        //物料操作日志
                        strSql += string.Format(@" INSERT INTO T_Bllb_MaterialLog_tbml(SerialNumber,CreateTime,OperateType,MaterialCode,QTY,Creator,Memo,SfcNo,PLCode)
SELECT SerialNumber,GETDATE(),'取消备料',MaterialCode,QTY,'{1}','单据'+S_Doc_NO,'','' FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}' AND RECEIVE_FLAG='N'", doc_no, Utils.uContext.UserNamek__BackingField);
                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                        ShowInfo("单据" + txt_SerialNumber.Text.Trim() + "取消备料成功", true);

                        return;
                    }
                    else
                    {
                        strSql = string.Format(@"SELECT COUNT(1) FROM T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}'", doc_no);
                        DataTable dt_c = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_c.Rows[0][0].ToString() != "0")
                        {
                            ShowInfo("单据已交接完成", false);

                        }
                        else
                        {
                            strSql += string.Format(@" DELETE FROM T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}'", doc_no);
                            strSql += string.Format(@" DELETE FROM T_Bllb_StorageDocSMT_tbds WHERE S_Doc_NO='{0}'", doc_no);
                            strSql += string.Format(@" DELETE FROM T_Bllb_StorageDoc_tbsd WHERE S_Doc_NO='{0}'", doc_no);
                            ShowInfo("单据未备料", false);
                        }
                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                    }
                    #endregion
                }
                else
                {
                    ShowInfo("输入信息无效", false);
                }

           
                return;
                #endregion

            }
        }

        private void ShowInfo(string msg, bool isOK)
        {
            lbl_msg.Text = msg;
            lbl_msg.ForeColor = isOK == true ? Color.Green : Color.Red;
            txt_SerialNumber.SelectAll();
        }
    }
}